"""
请求日志 | 业务层
"""

from biz.base_biz import (
    GetterBase,
    ValidatorBase,
)
from components.logger import log
from components.thread_pool import async_io_task
from mapping import RequestLogMapping
from models import PageSorting
from models.po import RequestLogPO
from models.request import RequestLogListRequest
from my_typing import *
from service import RequestLogService
from utils.decorator_utils import task_exc_catcher


class Model:
    """ 模型信息 """

    ID_FIELD: str = "request_log_id"
    NAME: str = "请求日志"
    PO = RequestLogPO
    SERVICE = RequestLogService


class RequestLogValidator(ValidatorBase):
    """ 请求日志 | 校验器 """

    model_id_field = Model.ID_FIELD
    model_name = Model.NAME
    model_po = Model.PO
    model_service = Model.SERVICE


class RequestLogGetter(GetterBase):
    """ 请求日志 | 获取器 """

    model_mapping = RequestLogMapping
    model_validator = RequestLogValidator

    @staticmethod
    def get_list_sorting(request: RequestLogListRequest) -> DictStrInt:
        return PageSorting.get_sorting_by_map(
            {
                "route_info.method": request.sort_by_method,
                "time_info.in_time": request.sort_by_request_time,
                "user_id": request.sort_by_user_id,
            }
        )

    @classmethod
    def get_list_query(cls, request: RequestLogListRequest) -> dict:
        condition = cls.Condition()

        condition.add_eq("request_id", value=request.request_id)
        condition.add_eq("route_info.method", value=request.method)
        condition.add_eq("route_info.path", value=request.path)
        condition.add_eq("user_id", value=request.user_id)
        condition.add_gte("time_info.in_time", value=request.request_time_start)
        condition.add_lte("time_info.in_time", value=request.request_time_end)
        condition.add_gte("time_info.total_seconds", value=request.use_time_min)
        condition.add_lte("time_info.total_seconds", value=request.use_time_max)
        condition.add_custom_query(
            value=request.object_id,
            query={
                "$or": [
                    {
                        "request_info.body": {
                            "$regex": str(request.object_id),
                        },
                    },
                    {
                        "response_info.body": {
                            "$regex": str(request.object_id),
                        },
                    },
                ]
            }
        )

        return condition.get_query()


class RequestLogSetter:
    """ 请求日志 | 设置器 """

    @staticmethod
    @async_io_task
    @task_exc_catcher(logger=log)
    def async_create_request_log(request_log_po: RequestLogPO) -> None:
        """ 异步创建 | 单条 | 请求日志 """

        RequestLogService.insert_one(request_log_po)
